﻿

using System.Net.Mail;
using iTeamyou.LTS.Core.Models;
using iTeamyou.LTS.Core.Services;
using iTeamyou.LTS.MigrationTool;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Console.WriteLine("Start");

var provider = new MigrationProvider();
//var skuList = provider.GetSKU();
//var supplierList = provider.GetSupplier();
//var channelList = provider.GetChannels();
//var manufacturerList = provider.GetManufacturer();
//var batchList = provider.GetBatch();
//var certProductList = provider.GetProductCert();
var certBatchList = provider.GetBatchCert();

var supplierService = new SupplierService();
var productService = new ProductService();
var manufacturerService = new ManufacturerService();
var batchService = new BatchService();

var createdBy = "SystemInit";
var urlBase = "https://lts.mannings.com.cn:5390/files/";
var pathBase = "D:\\iTeamyou\\LTS\\resources\\";
var fileBase = "/Users/alexli/Projects/iTeamyou.LTS/resources/";
var destFileBase = "/Users/alexli/Projects/iTeamyou.LTS/DestResources/";
var refFlowId = "Init2023";
var productLicenseType = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 23, 43 };
var supplierLicenseType = new List<int> { 23, 46, 44, 21, 28, 25, 42, 27, 37, 38, 26, 22 };
var manufacturerLicenseType = new List<int> { 21, 28, 32, 33, 34, 36, 37, 38, 39, 40, 42, 43, 44, 46 };
var batchLicenseType = new List<int> { 12 };

//批次证照
var list = batchService.GetList().Where(b => b.Number != "00000000");
foreach (var batch in list)
{
    var mangoBatch = provider.GetBatchByCode(batch.BId);
    var subjectId = mangoBatch.sku_id + "_" + mangoBatch.batch_number;
    var cert = certBatchList.Where(c => c.subject_id == subjectId).FirstOrDefault();
    if (cert != null)
    {
        var licenses = JsonConvert.DeserializeObject<List<ExtendInfo>>(cert.extend_info);
        if (licenses.Any())
        {
            foreach (var entry in licenses)
            {
                var license = provider.GetResourcesById(entry.id);
                if (license != null)
                {
                    var fileFullName = fileBase + license.id;
                    if (File.Exists(fileFullName))
                    {
                        var exist = batchService.GetLicenseByLId(license.id.ToString());
                        if (exist == null)
                        {
                            var inputLicense = new BatchLicense()
                            {
                                Id = Guid.NewGuid().ToString("N"),
                                LId = license.id.ToString(),
                                Name = license.name,
                                IsPublish = true,
                                CreatedBy = createdBy,
                                CreatedOn = Utils.ConvertLongToDateTime(license.update_time),
                                LastModifiedBy = createdBy,
                                LastModifiedOn = Utils.ConvertLongToDateTime(license.update_time),
                                //Type = supplierService.GetLicenseType("supplier").Where(t => t.RefId == entry.cert_type).FirstOrDefault().TypeId,
                                ValidFromDate = Utils.ConvertLongToDateTime(license.start_time),
                                ValidToDate = Utils.ConvertLongToDateTime(license.end_time),
                                EntryDatetime = batch.EntryDatetime,
                                OperationType = LicenseOp.Add,
                                BatchId = batch.Id,
                                Number = batch.Number
                            };

                            if (batchLicenseType.Any(p => p == entry.cert_type))
                                inputLicense.Type = manufacturerService.GetLicenseType("batch").Where(t => t.RefId == 42).FirstOrDefault().TypeId;
                            else
                                inputLicense.Type = manufacturerService.GetLicenseType("batch").Where(t => t.RefId == entry.cert_type).FirstOrDefault().TypeId;

                            var fileId = Guid.NewGuid().ToString("N");
                            var meta = JsonConvert.DeserializeObject<Meta>(license.meta);
                            var contentType = "";
                            var ext = meta.Ext;
                            if (!ext.StartsWith("."))
                                ext = "." + ext;
                            if (meta.Ext.Contains("pdf"))
                            {
                                contentType = "application/pdf";
                            }
                            else if (meta.Ext.Contains("png"))
                            {
                                contentType = "image/png";
                            }
                            else if (meta.Ext.Contains("jpg") || meta.Ext.Contains("jpeg"))
                            {
                                contentType = "image/jpeg";
                            }
                            var attachment = new BatchLicenseAttachment()
                            {
                                Name = license.name,
                                Id = fileId,
                                IsMain = true,
                                LicenseId = inputLicense.Id,
                                Path = pathBase + fileId + ext,
                                ContentType = contentType,
                                URL = urlBase + fileId + ext
                            };

                            using FileStream fs = new(fileFullName, FileMode.Open, FileAccess.Read);
                            using BinaryReader br = new BinaryReader(fs);
                            byte[] bytes = br.ReadBytes((int)fs.Length);
                            //attachment.FileContent = Convert.ToBase64String(bytes);
                            attachment.FileSize = (int)fs.Length;
                            using FileStream fsOut = new(destFileBase + fileId + ext, FileMode.CreateNew, FileAccess.ReadWrite);
                            fsOut.Write(bytes);
                            inputLicense.Attachments = new List<BatchLicenseAttachment>() { attachment };
                            inputLicense.RefFlowId = refFlowId;
                            batchService.UploadLicense(inputLicense);
                        }
                        //else if (!manufacturerLicenseType.Any(p => p == entry.cert_type))
                        //    Console.WriteLine($"New license Type:{entry.cert_type}");
                    }
                }
            }
        }
    }
}

//生产商证照
//var list = manufacturerService.GetList();
//foreach (var manufacturer in list)
//{
//    var mangoManufacturer = provider.GetManufacturerByCode(manufacturer.MId);
//    var cert = certProviderList.Where(c => c.subject_id == mangoManufacturer.id.ToString()).FirstOrDefault();
//    if (cert != null)
//    {
//        var licenses = JsonConvert.DeserializeObject<List<ExtendInfo>>(cert.extend_info);
//        if (licenses.Any())
//        {
//            foreach (var entry in licenses)
//            {
//                var license = provider.GetResourcesById(entry.id);
//                if (license != null)
//                {
//                    var fileFullName = fileBase + license.id;
//                    if (File.Exists(fileFullName))
//                    {
//                        var exist = manufacturerService.GetLicenseByLId(license.id.ToString());
//                        if (exist == null)
//                        {
//                            var inputLicense = new ManufacturerLicense()
//                            {
//                                Id = Guid.NewGuid().ToString("N"),
//                                LId = license.id.ToString(),
//                                Name = license.name,
//                                IsPublish = true,
//                                CreatedBy = createdBy,
//                                CreatedOn = Utils.ConvertLongToDateTime(license.update_time),
//                                LastModifiedBy = createdBy,
//                                LastModifiedOn = Utils.ConvertLongToDateTime(license.update_time),
//                                //Type = supplierService.GetLicenseType("supplier").Where(t => t.RefId == entry.cert_type).FirstOrDefault().TypeId,
//                                ValidFromDate = Utils.ConvertLongToDateTime(license.start_time),
//                                ValidToDate = Utils.ConvertLongToDateTime(license.end_time),
//                                ManufacturerId = manufacturer.Id,
//                                OperationType = LicenseOp.Add,
//                                ManufacturerName = manufacturer.Name
//                            };

//                            if (!manufacturerLicenseType.Any(p => p == entry.cert_type))
//                                inputLicense.Type = manufacturerService.GetLicenseType("manufacturer").Where(t => t.RefId == 42).FirstOrDefault().TypeId;
//                            else
//                                inputLicense.Type = manufacturerService.GetLicenseType("manufacturer").Where(t => t.RefId == entry.cert_type).FirstOrDefault().TypeId;

//                            var fileId = Guid.NewGuid().ToString("N");
//                            var meta = JsonConvert.DeserializeObject<Meta>(license.meta);
//                            var contentType = "";
//                            var ext = meta.Ext;
//                            if (!ext.StartsWith("."))
//                                ext = "." + ext;
//                            if (meta.Ext.Contains("pdf"))
//                            {
//                                contentType = "application/pdf";
//                            }
//                            else if (meta.Ext.Contains("png"))
//                            {
//                                contentType = "image/png";
//                            }
//                            else if (meta.Ext.Contains("jpg") || meta.Ext.Contains("jpeg"))
//                            {
//                                contentType = "image/jpeg";
//                            }
//                            var attachment = new ManufacturerLicenseAttachment()
//                            {
//                                Name = license.name,
//                                Id = fileId,
//                                IsMain = true,
//                                LicenseId = inputLicense.Id,
//                                Path = pathBase + fileId + ext,
//                                ContentType = contentType,
//                                URL = urlBase + fileId + ext
//                            };

//                            using FileStream fs = new(fileFullName, FileMode.Open, FileAccess.Read);
//                            using BinaryReader br = new BinaryReader(fs);
//                            byte[] bytes = br.ReadBytes((int)fs.Length);
//                            //attachment.FileContent = Convert.ToBase64String(bytes);
//                            attachment.FileSize = (int)fs.Length;
//                            using FileStream fsOut = new(destFileBase + fileId + ext, FileMode.CreateNew, FileAccess.ReadWrite);
//                            fsOut.Write(bytes);
//                            inputLicense.Attachments = new List<ManufacturerLicenseAttachment>() { attachment };
//                            inputLicense.RefFlowId = refFlowId;
//                            manufacturerService.UploadLicense(inputLicense);
//                        }
//                        else if (!manufacturerLicenseType.Any(p => p == entry.cert_type))
//                            Console.WriteLine($"New license Type:{entry.cert_type}");
//                    }
//                }
//            }
//        }
//    }
//}

//供应商证照
//var list = supplierService.GetList();
//foreach (var supplier in list)
//{
//    var mangoSupplier = provider.GetSupplierByCode(supplier.SId);
//    var cert = certProviderList.Where(c => c.subject_id == mangoSupplier.id.ToString()).FirstOrDefault();
//    if (cert != null)
//    {
//        var licenses = JsonConvert.DeserializeObject<List<ExtendInfo>>(cert.extend_info);
//        if (licenses.Any())
//        {
//            foreach (var entry in licenses)
//            {
//                var license = provider.GetResourcesById(entry.id);
//                if (license != null)
//                {
//                    var fileFullName = fileBase + license.id;
//                    if (File.Exists(fileFullName))
//                    {
//                        var exist = supplierService.GetLicenseByLId(license.id.ToString());
//                        if (exist == null)
//                        {
//                            var inputLicense = new SupplierLicense()
//                            {
//                                Id = Guid.NewGuid().ToString("N"),
//                                LId = license.id.ToString(),
//                                Name = license.name,
//                                IsPublish = true,
//                                CreatedBy = createdBy,
//                                CreatedOn = Utils.ConvertLongToDateTime(license.update_time),
//                                LastModifiedBy = createdBy,
//                                LastModifiedOn = Utils.ConvertLongToDateTime(license.update_time),
//                                //Type = supplierService.GetLicenseType("supplier").Where(t => t.RefId == entry.cert_type).FirstOrDefault().TypeId,
//                                ValidFromDate = Utils.ConvertLongToDateTime(license.start_time),
//                                ValidToDate = Utils.ConvertLongToDateTime(license.end_time),
//                                SupplierId = supplier.Id,
//                                OperationType = LicenseOp.Add,
//                                SupplierName = supplier.Name
//                            };

//                            if (!supplierLicenseType.Any(p => p == entry.cert_type))
//                                inputLicense.Type = supplierService.GetLicenseType("supplier").Where(t => t.RefId == 42).FirstOrDefault().TypeId;
//                            else
//                                inputLicense.Type = supplierService.GetLicenseType("supplier").Where(t => t.RefId == entry.cert_type).FirstOrDefault().TypeId;

//                            var fileId = Guid.NewGuid().ToString("N");
//                            var meta = JsonConvert.DeserializeObject<Meta>(license.meta);
//                            var contentType = "";
//                            var ext = meta.Ext;
//                            if (!ext.StartsWith("."))
//                                ext = "." + ext;
//                            if (meta.Ext.Contains("pdf"))
//                            {
//                                contentType = "application/pdf";
//                            }
//                            else if (meta.Ext.Contains("png"))
//                            {
//                                contentType = "image/png";
//                            }
//                            else if (meta.Ext.Contains("jpg") || meta.Ext.Contains("jpeg"))
//                            {
//                                contentType = "image/jpeg";
//                            }
//                            var attachment = new SupplierLicenseAttachment()
//                            {
//                                Name = license.name,
//                                Id = fileId,
//                                IsMain = true,
//                                LicenseId = inputLicense.Id,
//                                Path = pathBase + fileId + ext,
//                                ContentType = contentType,
//                                URL = urlBase + fileId + ext
//                            };

//                            using FileStream fs = new(fileFullName, FileMode.Open, FileAccess.Read);
//                            using BinaryReader br = new BinaryReader(fs);
//                            byte[] bytes = br.ReadBytes((int)fs.Length);
//                            attachment.FileContent = Convert.ToBase64String(bytes);
//                            attachment.FileSize = (int)fs.Length;
//                            using FileStream fsOut = new(destFileBase + fileId + ext, FileMode.CreateNew, FileAccess.ReadWrite);
//                            fsOut.Write(bytes);
//                            inputLicense.Attachments = new List<SupplierLicenseAttachment>() { attachment };
//                            inputLicense.RefFlowId = refFlowId;
//                            supplierService.UploadLicense(inputLicense);
//                        }
//                        else if (!supplierLicenseType.Any(p => p == entry.cert_type))
//                            Console.WriteLine($"New license Type:{entry.cert_type}");
//                    }
//                }
//            }
//        }
//    }
//}


//商品证照
//var productList = productService.GetList();
//foreach (var product in productList)
//{
//    var sku = provider.GetSKUByBarcode(product.UPC);
//    var cert = certProductList.Where(c => c.subject_id == sku.id.ToString()).FirstOrDefault();
//    if (cert != null)
//    {
//        var licenses = JsonConvert.DeserializeObject<List<ExtendInfo>>(cert.extend_info);
//        if (licenses.Any())
//        {
//            foreach (var entry in licenses)
//            {
//                var license = provider.GetResourcesById(entry.id);
//                if (license != null)
//                {
//                    var fileFullName = fileBase + license.id;
//                    if (File.Exists(fileFullName))
//                    {
//                        var exist = productService.GetLicenseByLId(license.id);
//                        if (productLicenseType.Any(p => p == entry.cert_type) && exist == null)
//                        {
//                            var inputLicense = new ProductLicense()
//                            {
//                                Id = Guid.NewGuid().ToString("N"),
//                                LId = license.id,
//                                Name = license.name,
//                                IsPublish = true,
//                                CreatedBy = createdBy,
//                                CreatedOn = Utils.ConvertLongToDateTime(license.update_time),
//                                LastModifiedBy = createdBy,
//                                LastModifiedOn = Utils.ConvertLongToDateTime(license.update_time),
//                                Type = productService.GetLicenseType("product").Where(t => t.RefId == entry.cert_type).FirstOrDefault().TypeId,
//                                ValidFromDate = Utils.ConvertLongToDateTime(license.start_time),
//                                ValidToDate = Utils.ConvertLongToDateTime(license.end_time),
//                                ProductId = product.Id,
//                                OperationType = LicenseOp.Add,
//                                ProductName = product.Name
//                            };
//                            var fileId = Guid.NewGuid().ToString("N");
//                            var meta = JsonConvert.DeserializeObject<Meta>(license.meta);
//                            var contentType = "";
//                            var ext = meta.Ext;
//                            if (!ext.StartsWith("."))
//                                ext = "." + ext;
//                            if (meta.Ext.Contains("pdf"))
//                            {
//                                contentType = "application/pdf";
//                            }
//                            else if (meta.Ext.Contains("png"))
//                            {
//                                contentType = "image/png";
//                            }
//                            else if (meta.Ext.Contains("jpg") || meta.Ext.Contains("jpeg"))
//                            {
//                                contentType = "image/jpeg";
//                            }
//                            var attachment = new ProductLicenseAttachment()
//                            {
//                                Name = license.name,
//                                Id = fileId,
//                                IsMain = true,
//                                LicenseId = inputLicense.Id,
//                                Path = pathBase + fileId + ext,
//                                ContentType = contentType,
//                                URL = urlBase + fileId + ext
//                            };

//                            using FileStream fs = new(fileFullName, FileMode.Open, FileAccess.Read);
//                            using BinaryReader br = new BinaryReader(fs);
//                            byte[] bytes = br.ReadBytes((int)fs.Length);
//                            attachment.FileContent = Convert.ToBase64String(bytes);
//                            attachment.FileSize = (int)fs.Length;
//                            using FileStream fsOut = new(destFileBase + fileId + ext, FileMode.CreateNew, FileAccess.ReadWrite);
//                            fsOut.Write(bytes);
//                            inputLicense.Attachments = new List<ProductLicenseAttachment>() { attachment };
//                            inputLicense.RefFlowId = refFlowId;
//                            productService.UploadLicense(inputLicense);
//                        }
//                        else if (!productLicenseType.Any(p => p == entry.cert_type))
//                            Console.WriteLine($"New license Type:{entry.cert_type}");
//                    }
//                }
//            }
//        }
//    }
//}

//供应商
//foreach (var supplier in supplierList)
//{
//supplierService.Save(new Supplier()
//{
//    Id = Guid.NewGuid().ToString("N"),
//    SId = supplier.code,
//    Contact = supplier.contact_name,
//    ContactNumber = supplier.contact_phone,
//    Name = supplier.name,
//    Status = supplier.status == 1 ? Status.InCooperation : Status.Noncooperation,
//    LastModifiedOn = Utils.ConvertLongToDateTime(supplier.update_time),
//    LastModifiedBy = "SystemInit",
//    CreatedBy = "SystemInit",
//    CreatedOn = Utils.ConvertLongToDateTime(supplier.create_time),
//});

//}

//商品
//foreach (var product in skuList)
//{
//    var channel = channelList.Where(c => c.source_sku == product.id).FirstOrDefault();
//    if (channel != null)
//    {
//        var saveProduct = new Product()
//        {
//            Id = Guid.NewGuid().ToString("N"),
//            PId = channel?.sku_code.ToString(),
//            Name = product.name,
//            UPC = product.barcode,
//            LastModifiedOn = Utils.ConvertLongToDateTime(product.update_time),
//            LastModifiedBy = "SystemInit",
//            CreatedBy = "SystemInit",
//            CreatedOn = Utils.ConvertLongToDateTime(product.create_time),
//        };

//        if (!string.IsNullOrEmpty(channel.specification))
//            saveProduct.Specification = JsonConvert.DeserializeObject<List<JObject>>(channel?.specification)?.FirstOrDefault()["val"]?.ToString();

//        var exist = productService.GetBySKU(saveProduct.PId);
//        if (exist == null)
//            productService.Save(saveProduct);
//    }
//}

//生产商
//foreach (var manufacturer in manufacturerList)
//{
//    manufacturerService.Save(new Manufacturer()
//    {
//        Id = Guid.NewGuid().ToString("N"),
//        MId = manufacturer.code,
//        Name = manufacturer.name,
//        Register = manufacturer.contact_name,
//        LastModifiedOn = Utils.ConvertLongToDateTime(manufacturer.update_time),
//        LastModifiedBy = "SystemInit",
//        CreatedBy = "SystemInit",
//        CreatedOn = Utils.ConvertLongToDateTime(manufacturer.create_time),
//    });
//}

//批次
//foreach (var batch in batchList.Skip(90699))
//{
//    //Console.WriteLine($"BatchID: {batch.id}");
//    var exist = batchService.GetByID(batch.id.ToString());
//    if (!exist.Any())
//    {
//        //两边系统对应不上，number和ordernumber在lts1.0中有为空，lts2.0不能为空，
//        //若两个字段有为空时，用00000000填充
//        var saveBatch = new Batch()
//        {
//            Id = Guid.NewGuid().ToString("N"),
//            BId = batch.id.ToString(),
//            OrderNumber = batch.purchase_number ?? "00000000",
//            Number = batch.batch_number ?? "00000000",
//            Quantity = batch.num,
//            EntryDatetime = Utils.ConvertLongToDateTime(batch.store_time),
//            WarehouseNumber = batch.id.ToString(),
//            ProducedDate = batch.production_date,
//            LastModifiedOn = Utils.ConvertLongToDateTime(batch.update_time),
//            LastModifiedBy = "SystemInit",
//            CreatedBy = "SystemInit",
//            CreatedOn = Utils.ConvertLongToDateTime(batch.create_time),
//        };
//        var sku = channelList.Where(s => s.id == batch.sku_id).FirstOrDefault();
//        var supplier = supplierList.Where(s => s.id == batch.provider_id.ToString()).FirstOrDefault();
//        if (sku != null && !string.IsNullOrEmpty(sku.sku_code.ToString()))
//        {
//            var product = productService.GetBySKU(sku.sku_code.ToString());
//            saveBatch.ProductId = product?.Id;
//        }

//        if (supplier != null && !string.IsNullOrEmpty(supplier.code))
//        {
//            var sp = supplierService.GetByCode(supplier.code);
//            saveBatch.SupplierId = sp.FirstOrDefault()?.Id;
//        }
//        batchService.Save(saveBatch);
//    }
//}


//Console.WriteLine($"SKU Count:{skuList.Count}");
//Console.WriteLine($"Supplier Count:{supplierList.Count}");
//Console.WriteLine($"Manufacturer Count:{manufacturerList.Count}");
//Console.WriteLine($"Batch Count:{batchList.Count}");
Console.Read();